//当前编辑的时间段id
var curEditingDurationId;
//当前编辑的时间段起始时间
var startTime = "";
//当前编辑的时间段结束时间
var endTime = "";

//当前筛选分组id
var curGroupId;
//产品线为蜜哆哆
var goodsType = 0;

// 已添加和待添加表格实例
var $tableExist = $("#exist-buying-goods");
var $tableAdd = $("#add-buying-goods");

var durationList = [];

//一级分组列表，渲染select中的optgroup
var firstGroupArr = [];
//二级分组,渲染select中的option
var secondGroupArr = [];
$(function () {
    //生成分组下拉框
    executeGetFirstSecGroup(goodsType);
    //初始化已有推荐和待选推荐表格
    initExistTable();
    initAddTable();
});

var todayRange = {
    elem: "#todayRange",
    type: "datetime",
    range: "至",
    /* Object
     date: 22
     hours: 0
     minutes: 0
     month: 9
     seconds: 0
     year: 2017*/
    done: function (value, date, endDate) {
        // alert(value);

        // startTime: 2017-09-21 00:00:00
        startTime = value.slice(0, 19).toString();
        console.log("startTime:", value.slice(0, 19).toString())
        // endTime: 2017-09-29 00:00:00
        endTime = value.slice(-19).toString();
        console.log("endTime:", value.slice(-19).toString())
        //value: 2017-09-06 00:00:00 至 2017-09-15 00:00:00
        console.log("value:", value);
        console.log("date:", date);
        console.log("endDate:", endDate);
    }
}

laydate.render(todayRange);

//去管理抢购
function manageBuying() {

    getDurationAndGenerateSelect({});
    $("#btn-add").show();
    $("#btn-manage").hide();
    $("#mng-div").show();
    $("#add-div").hide();
}

//获取时间段，生成新的下拉框并更新exist-table
function getDurationAndGenerateSelect(postData) {
    $.ajax({
        url: urlcore + "/api/panicBuyingTime/selectByCondition",
        method: "post",
        dataType: "json",
        // async: false,//禁止异步
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(postData),
        success: function (cbdata) {
            console.log(cbdata.data);
            durationList = cbdata.data;
            curEditingDurationId = "";
            $tableExist.bootstrapTable("refresh");
            //生成选择时间段的optgroup
            generateDurationOptgroupHtml(durationList);

        },
        error: function (data) {
            alert("获取时间段失败");
        }
    });
}

//去添加
function goAddBuying() {
    // 重置时间段
    curEditingDurationId = "";
    $("#todayRange").attr("disabled", false);
    $("#todayRange").val("");

    $tableExist.bootstrapTable("refresh");

    $("#mng-div").hide();
    $("#add-div").show();
    $("#btn-add").hide();
    $("#btn-manage").show();


}

// 删除所选整个时间段及商品
function delCurDuration() {
    curEditingDurationId = curEditingDurationId;
    $.ajax({
        url: urlcore + "/api/panicBuyingGoods/delAllPanicBuyingByDurationId",
        method: "get",
        dataType: "json",
        contentType: "application/json;charset=UTF-8",
        data: {
            pbtId: curEditingDurationId
        },
        success: function (data) {
            //获取时间段，生成新的下拉框并更新exist-table
            getDurationAndGenerateSelect({});
            alert("删除抢购时间段成功");
        },
        error: function (data) {
            alert("删除抢购时间失败");
        }
    });
}

//抢购时间段改变，在管理抢购商品时刷新列表
$("#curDuration").change(function () {
    curEditingDurationId = $("#curDuration").val();
    $tableExist.bootstrapTable("refresh");
    /*  initExistTable();
      initAddTable();*/
});

//保存当前编辑的时间段
function saveCurDuration() {
    if ("" == $("#todayRange").val()) {
        alert("请先选择时间段");
        return;
    }
    var postData = {
        startDate: startTime,
        endDate: endTime
    }
    $.ajax({
        url: urlcore + "/api/panicBuyingTime/add",
        method: "post",
        dataType: "json",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(postData),
        success: function (data) {
            //返回抢购时间段id，赋值到选择时间上
            curEditingDurationId = data.data.id;
            console.log("抢购时间id:", curEditingDurationId);
            $("#todayRange").attr("disabled", true);
            alert("保存抢购时间段成功，请添加商品");
        },
        error: function (data) {
            alert("保存抢购时间失败");
        }
    });
}

// 重置时间段
function resetCurDuration() {
    curEditingDurationId = "";
    $("#todayRange").attr("disabled", false);
    $("#todayRange").val("");
    alert("已重置时间段");

}

// 继续添加
function continueAdd() {
    window.location.reload();
}

//初始化已有推荐列表
function initExistTable() {
    var url = urlcore + "/api/panicBuyingGoods/getPanicedGoodsPageWithDurationId";
    initTable($tableExist, columnsExist, url, 0);
}

//初始化待选推荐列表
function initAddTable() {
    var url = urlcore + "/api/panicBuyingGoods/getUnPanicedGoodsListWithCategory";
    initTable($tableAdd, columnsAdd, url, 1);
}

var columnsExist = [
    {
        checkbox: true,
    }, {
        title: "序号",
        align: "center",
        width: "50px",
        formatter: function (value, row, index) {
            return (index + 1);
        }
    }, {
        field: "id",
        title: "限时抢购id",
        halign: "center",
        align: "center",
        width: "80px",
        // visible: false
    }, {
        field: "goodsId",
        title: "商品ID",
        halign: "center",
        align: "center",
        width: "80px",
        visible: false
    }, {
        field: "goodsName",
        title: "商品名称",
        halign: "center",
        sortable: true
    }, {
        field: "returnRate",
        title: "哆币返现率",
        halign: "center",
        valign: "middle",
        align: "center",
        width: "80px",
    },{
        field: "timeReturnRate",
        title: "限时返现率(如0.25)",
        halign: "center",
        valign: "middle",
        align: "center",
        width: "80px",
        formatter: function (value, row, index) {
            if (value === null)
                value = "";
            return '<input class="time-returnrate-input form-control" type="text" value="' + value + '">';
        }
    }, {
        field: "num",
        title: "限购数量",
        halign: "center",
        valign: "middle",
        align: "center",
        width: "80px",
        formatter: function (value, row, index) {
            if (value === null)
                value = "";
            return '<input class="limit-num form-control" type="text" value="' + value + '">';
        }
    }, {
        field: "goodsUrl",
        title: "商品图片",
        align: "center",
        width: "50px",
        formatter: function (value, row, index) {
            return '<img style="width: 50px;height: auto" src="' + value + '" >';
        }
    },{
        title: "操作",
        halign: "center",
        sortable: true,
        align:"center",
        width: "150px",
        formatter: function (value, row, index) {
            var optHtml = "";
            if(undefined!=row.isHomepage&&row.isHomepage==1){
                //首页显示
                optHtml += "<a class=\"btn btn-primary btn-xs\" href=\"javascript:;\" onclick=\"homepageDisp(" + row.id+","+"0" + ")\"> 取消置顶</a>\n";
            }else {
                //首页显示
                optHtml += "<a class=\"btn btn-primary btn-xs\" href=\"javascript:;\" onclick=\"homepageDisp(" + row.id+","+"1" + ")\"> 置顶</a>\n";
            }

            return optHtml;
        }
    }];
var columnsAdd = [
    {
        checkbox: true,
    }, {
        title: "序号",
        align: "center",
        width: "50px",
        formatter: function (value, row, index) {
            return (index + 1);
        }
    }, {
        field: "id",
        title: "商品ID",
        halign: "center",
        align: "center",
        width: "80px",
        visible: false
    }, {
        field: "goodsName",
        title: "商品名称",
        halign: "center",
        sortable: true
    }, {
        field: "mPrice",
        title: "商品价格",
        halign: "center",
        align: "center",
        width: "80px",
    }, {
        field: "returnRate",
        title: "哆币返现率",
        halign: "center",
        valign: "middle",
        align: "center",
        width: "80px",

    },
    {
        field: "goodsUrl",
        title: "商品图片",
        align: "center",
        width: "50px",
        formatter: function (value, row, index) {
            return '<img style="width: 50px;height: auto" src="' + value + '" >';
        }
    }, {
        title: "操作",
        halign: "center",
        sortable: true,
        align:"center",
        width: "150px",
        formatter: function (value, row, index) {
            var optHtml = "";
            //添加到今日特卖
            optHtml += "<a class=\"btn btn-primary btn-xs\" href=\"javascript:;\" onclick=\"addToList(" + row.id + ")\"> 添加</a>\n";
            return optHtml;
        }
    }];

var queryParams = function (params, tag) {
    console.log("params:", params);
    console.log("tag:", tag);
    var param;
    if (tag == 0) {
        param = {
            goods: {
                // id: goodsId
            },
            page: {
                offset: params.offset,
                current: params.offset / params.limit + 1,//bootstrap-table分页参数offset从0开始，计算的后端当前页参数current=(offset/limit+1)，
                size: params.limit
            },
            searchText: params.search,
            //查询当前抢购时间段的商品信息，参数为当前时间段id
            intParam: curEditingDurationId
        };
    }

    //待选推荐
    if (tag === 1) {
        param = {
            goods: {
                // id: goodsId,
                // "classifyId":classifyId,
                indexGroupId: curGroupId,
                // goodsType: goodsType
            },
            page: {
                offset: params.offset,
                current: params.offset / params.limit + 1,//bootstrap-table分页参数offset从0开始，计算的后端当前页参数current=(offset/limit+1)，
                size: params.limit
            },
            searchText: params.search
        };
    }
    return param;
};

//初始化表格，有已有和待选的商品两类表格 tableins:表格实例 ,
// insTag 0表示当前已添加表格 1表示待添加的表格
function initTable(tableins, columns, url, insTag) {
    tableins.bootstrapTable({
        columns: columns,
        method: "post",
        url: url,
        dataType: "json",
        queryParams: function (params) {
            return queryParams(params, insTag);
        },
        //返回数据预处理
        responseHandler: function (cbdata) {
            console.log(cbdata);
            if (null != cbdata.data && null != cbdata.data.records) {
                var records = cbdata.data.records;
                var res = {
                    //如果采用server端分页，必须有rows和total这两部分数据
                    "rows": records,
                    "total": cbdata.data.total
                };
                return res;
            } else return {"rows": [], "total": 0};
        },
        cache: false,
        // toolbar: '#toolbar',//自定义工具栏，不同表格工具栏不同，一个jQuery 选择器，指明自定义的toolbar 例如:#toolbar, .toolbar.
        pagination: true,//启用分页条
        sidePagination: "server",//分页方式client或server
        // pageNumber: 1,
        pageSize: 16,//每页大小
        pageList: [16, 32, 48, 64],//可以选择每页大小
        showRefresh: true,//显示刷新
        sortable: true,//是否启用排序
        clickToSelect: true,//设置true 将在点击行时，自动选择rediobox 和 checkbox
        search: true,//只是客户端搜索
        // searchText:"",//初始搜索文本
    });
}

// 保存修改
function saveFromExist() {
    var uptBuyingList = [];
    //traversal
    $("#exist-buying-goods > tbody tr").each(function () {
        var buyingId = $(this).find("td").eq(2).text();
        var timeReturnRate = $(this).find("input[class*='time-returnrate-input']").eq(0).val();
        var num = $(this).find("input[class*='limit-num']").eq(0).val();
        /* alert("buyingId: "+buyingId);
         alert("timeReturnRate: "+time_rate);
         alert("num: "+num);*/
        uptBuyingList.push({
            id: buyingId,
            timeReturnRate: timeReturnRate,
            num: num
        });
    });

    $.ajax({
        type: "POST",
        url: urlcore + "/api/panicBuyingGoods/uptTodayBuyingBatch",
        dataType: "json",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(uptBuyingList),
        success: function (data) {
            alert("抢购商品信息修改成功！");
            console.log("batchdata", data);
            $tableExist.bootstrapTable("refresh");
        },
        error: function () {

        }
    });
}

// 点击移除按钮移出已推荐表
function rmFromExist() {
    //get selections arr
    var selection = $tableExist.bootstrapTable('getSelections');
    if (selection.length == 0) {
        alert("请先选择商品");
        return;
    }
    console.log(selection);
    confirm("确认从抢购列表中移除吗，不会影响到商品状态", function (callback) {
        if (callback) {
            rmRec();
        }
    });

    function rmRec() {
        var paramArr = [];
        for (var item of selection) {
            paramArr.push({
                id: item.id,
            })
        }
        $.ajax({
            type: "POST",
            url: urlcore + "/api/panicBuyingGoods/deleteTodayBuyingGoodsBatch",
            dataType: "json",
            contentType: "application/json;charset=UTF-8",
            data: JSON.stringify(paramArr),
            success: function (data) {
                $tableExist.bootstrapTable('refresh');
                $tableAdd.bootstrapTable('refresh');
                console.log("rmbatchgoodsdata", data);
                alert("批量移除商品成功！");
            },
            error: function () {
                alert("失败");
            }
        });
    }
}

//点击按钮添加到商品抢购，更新已添加抢购表,gId不为undefined的时候为单个添加
function addToList(gId) {
    if (undefined == curEditingDurationId || "" == curEditingDurationId) {
        alert("请先选择或保存时间段");
        return;
    }
    var paramArr = [];
    if (gId != undefined) {
        paramArr.push({
            goodsId: gId,
            status: 1,//抢购商品状态1正常2已抢完，默认添加时为1
            timeReturnRate: 0.25,//限时返现率，默认为0.25
            attentionNum: 0,//关注数，默认为0
            pbtId: curEditingDurationId,
        })
    } else {
        var selection = $tableAdd.bootstrapTable('getSelections');
        if (selection.length == 0) {
            alert("请先选择商品");
            return;
        }
        //get selections arr
        console.log(selection);

        for (var item of selection) {
            paramArr.push({
                goodsId: item.id,
                status: 1,//抢购商品状态1正常2已抢完，默认添加时为1
                timeReturnRate: 0.25,//限时返现率，默认为0.25
                attentionNum: 0,//关注数，默认为0
                pbtId: curEditingDurationId,
            })
        }
    }
    $.ajax({
        type: "POST",
        url: urlcore + "/api/panicBuyingGoods/addTodayBuyingGoodsBatch",
        dataType: "json",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(paramArr),
        success: function (data) {
            $tableExist.bootstrapTable('refresh');
            $tableAdd.bootstrapTable('refresh');
            console.log("batchgoodsdata", data);
            alert("批量添加抢购商品成功，请修改已添加的抢购商品的限时返现率和限购数量！");
        },
        error: function () {
            alert("添加失败");
        }
    });
    //refresh table
}

//设置主页显示，取消主页显示
function homepageDisp(id,targetIsHomepage) {
    if(undefined==id||undefined==targetIsHomepage){
        alert("必须要有id和目标显示状态");
        return
    }
    var panicUptGoods={
        id:id,
        isHomepage:targetIsHomepage
    }
    $.ajax({
        type:"post",
       url:urlcore+"/api/panicBuyingGoods/update" ,
        dataType: "json",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(panicUptGoods),
        success: function (data) {
            console.log("uptdata", data);
            $tableExist.bootstrapTable("refresh");
        },
        error: function () {

        }

    });
}


//分组改变，在管理分组商品时刷新列表
$("#curGroup").change(function () {
    curGroupId = $("#curGroup").val();
    $tableAdd.bootstrapTable("refresh");
});

//获取一二级分组（分开）
function executeGetFirstSecGroup(selectedGroupType) {
    $.ajax({
        url: urlcore + "/api/indexGroup/getAllGroup",
        method: "get",
        dataType: "json",
        // async: false,//禁止异步
        contentType: "application/json;charset=UTF-8",
        data: {
            groupType: selectedGroupType,
        },
        success: function (cbdata) {
            console.log(cbdata.data);
            firstGroupArr = cbdata.data.firstGroupList;
            secondGroupArr = cbdata.data.secondGroupList;
            //生成选择分组的optgroup
            generateOptgroupHtml(firstGroupArr, secondGroupArr);
        },
        error: function (data) {
            alert("获取分组失败");
        }
    });
}

//生成选择分组的optgroup
function generateOptgroupHtml(firstGroupArr, secondGroupArr) {

    var optgroupHtmlStr = "";
    //生成optgroup
    for (var item of firstGroupArr) {
        var htmlStr = getGroupOptionHtml(item, 0);
        optgroupHtmlStr += htmlStr;
    }
    $("#curGroup").append(optgroupHtmlStr);

    //生成optgroup的option
    for (var item of secondGroupArr) {
        var htmlStr = getGroupOptionHtml(item, 1);
        var parentId = item.pid;
        $("#curGroup").find('optgroup[data-id="' + parentId + '"]').append(htmlStr);
    }
}

//生成分组选择框的optgroup（tag为0）或option（tag为1）
function getGroupOptionHtml(item, tag) {
    var htmlStr = "";
    if (tag == 0) {
        htmlStr = "   <optgroup data-id=\"" + item.id + "\" label=\"" + item.title + "\">\n" +
            "    </optgroup>";
    }
    if (tag == 1) {
        htmlStr = "<option value=\"" + item.id + "\">" + item.title + "</option>";
    }
    return htmlStr;
}

//生成抢购时间段html
function generateDurationOptgroupHtml(durationList) {
    $("#curDuration").html("");
    var optionHtmlStr = "";
    //生成optgroup
    for (var item of durationList) {
        var startT = formatDate(item.startDate);
        var endT = formatDate(item.endDate);
        var htmlStr = "";
        htmlStr = "<option value=\"" + item.id + "\">" + startT + "至" + endT + "</option>";
        optionHtmlStr += htmlStr;
    }
    $("#curDuration").append(optionHtmlStr);
    curEditingDurationId = $("#curDuration").val();
    $tableExist.bootstrapTable("refresh");
}

//将时间戳格式化为yyyy-MM-dd hh:mm:ss形式
function formatDate(timestamp) {
    var date = new Date(timestamp);
    Y = date.getFullYear() + '-';
    M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    D = date.getDate() + ' ';
    h = date.getHours() + ':';
    // m = (date.getMinutes()<10?'0'+date.getMinutes():date.getMinutes()) + ':';
    m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
    s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
    // var result = Y + M + D + h + m + s;
    var result = Y + M + D + h + m;
    return result;
}

// console.log(formatDate(1398250549490));